<template>
  <div class="discover-tab">
    <!-- 筛选栏 -->
    <el-card class="filter-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.style" placeholder="风格筛选" @change="loadOutfits">
            <el-option label="全部风格" value="" />
            <el-option label="休闲" value="casual" />
            <el-option label="商务" value="business" />
            <el-option label="正式" value="formal" />
            <el-option label="时尚" value="trendy" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.season" placeholder="季节筛选" @change="loadOutfits">
            <el-option label="全部季节" value="" />
            <el-option label="春季" value="spring" />
            <el-option label="夏季" value="summer" />
            <el-option label="秋季" value="autumn" />
            <el-option label="冬季" value="winter" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.sortBy" placeholder="排序方式" @change="loadOutfits">
            <el-option label="最新发布" value="latest" />
            <el-option label="最受欢迎" value="popular" />
            <el-option label="评分最高" value="rating" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="refreshOutfits">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 搭配网格 -->
    <div class="outfits-grid" v-loading="loading">
      <div 
        v-for="outfit in outfits" 
        :key="outfit.id"
        class="outfit-card"
      >
        <el-card shadow="hover">
          <!-- 搭配图片 -->
          <div class="outfit-image-container">
            <img 
              :src="outfit.main_image || '/placeholder-outfit.png'" 
              :alt="outfit.name"
              class="outfit-image"
              @click="viewOutfitDetail(outfit)"
            />
            <div class="outfit-overlay">
              <div class="outfit-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ outfit.view_count || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><Star /></el-icon>
                  {{ outfit.like_count || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ outfit.comment_count || 0 }}
                </span>
              </div>
            </div>
          </div>

          <!-- 搭配信息 -->
          <div class="outfit-info">
            <div class="outfit-header">
              <h4 class="outfit-title">{{ outfit.name }}</h4>
              <el-rate 
                v-model="outfit.rating" 
                disabled 
                show-score 
                text-color="#ff9900"
                score-template="{value}"
              />
            </div>
            
            <div class="outfit-tags">
              <el-tag 
                v-if="outfit.style" 
                size="small" 
                type="primary"
              >
                {{ outfit.style }}
              </el-tag>
              <el-tag 
                v-if="outfit.season" 
                size="small" 
                type="success"
              >
                {{ outfit.season }}
              </el-tag>
            </div>

            <!-- 用户信息 -->
            <div class="user-info">
              <img 
                :src="outfit.user?.avatar || '/placeholder-avatar.png'" 
                :alt="outfit.user?.username"
                class="user-avatar"
              />
              <span class="username">{{ outfit.user?.username }}</span>
              <span class="publish-time">{{ formatDate(outfit.created_at) }}</span>
            </div>

            <!-- 操作按钮 -->
            <div class="outfit-actions">
              <el-button 
                size="small" 
                :type="outfit.isLiked ? 'primary' : ''"
                @click="toggleLike(outfit)"
              >
                <el-icon><Star /></el-icon>
                {{ outfit.isLiked ? '已点赞' : '点赞' }}
              </el-button>
              <el-button 
                size="small" 
                @click="showComments(outfit)"
              >
                <el-icon><ChatDotRound /></el-icon>
                评论
              </el-button>
              <el-button 
                size="small" 
                @click="shareOutfit(outfit)"
              >
                <el-icon><Share /></el-icon>
                分享
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="load-more" v-if="hasMore">
      <el-button 
        @click="loadMore" 
        :loading="loadingMore"
        size="large"
      >
        加载更多
      </el-button>
    </div>

    <!-- 评论对话框 -->
    <el-dialog v-model="commentDialogVisible" title="评论" width="600px">
      <div class="comments-container">
        <!-- 评论列表 -->
        <div class="comments-list" v-loading="loadingComments">
          <div 
            v-for="comment in comments" 
            :key="comment.id"
            class="comment-item"
          >
            <img 
              :src="comment.user?.avatar || '/placeholder-avatar.png'" 
              :alt="comment.user?.username"
              class="comment-avatar"
            />
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-username">{{ comment.user?.username }}</span>
                <span class="comment-time">{{ formatDate(comment.created_at) }}</span>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
              <div class="comment-actions">
                <el-button size="small" text @click="replyComment(comment)">
                  回复
                </el-button>
                <el-button size="small" text @click="likeComment(comment)">
                  <el-icon><Star /></el-icon>
                  {{ comment.like_count || 0 }}
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 发表评论 -->
        <div class="comment-form">
          <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            placeholder="写下您的评论..."
            maxlength="500"
            show-word-limit
          />
          <div class="comment-form-actions">
            <el-rate v-model="commentRating" />
            <el-button 
              type="primary" 
              @click="submitComment"
              :loading="submittingComment"
            >
              发表评论
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { socialAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const loadingComments = ref(false)
const submittingComment = ref(false)
const commentDialogVisible = ref(false)

const outfits = ref([])
const comments = ref([])
const currentPage = ref(1)
const hasMore = ref(true)
const currentOutfit = ref(null)

const newComment = ref('')
const commentRating = ref(0)

// 筛选条件
const filters = reactive({
  style: '',
  season: '',
  sortBy: 'latest'
})

// 加载搭配列表
const loadOutfits = async (reset = true) => {
  try {
    if (reset) {
      loading.value = true
      currentPage.value = 1
      outfits.value = []
    } else {
      loadingMore.value = true
    }

    const response = await socialAPI.getPublicOutfits({
      page: currentPage.value,
      pageSize: 20,
      ...filters
    })

    if (response.code === 200) {
      const newOutfits = response.data.list || []
      
      if (reset) {
        outfits.value = newOutfits
      } else {
        outfits.value.push(...newOutfits)
      }

      hasMore.value = newOutfits.length === 20
    } else {
      throw new Error(response.message || '获取搭配列表失败')
    }
  } catch (error) {
    console.error('获取搭配列表失败:', error)
    ElMessage.error('获取搭配列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  currentPage.value++
  loadOutfits(false)
}

// 刷新搭配
const refreshOutfits = () => {
  loadOutfits(true)
}

// 查看搭配详情
const viewOutfitDetail = (outfit) => {
  // 这里应该跳转到搭配详情页面
  console.log('查看搭配详情:', outfit)
}

// 切换点赞
const toggleLike = async (outfit) => {
  try {
    const response = await socialAPI.likeOutfit(outfit.id)
    
    if (response.code === 200) {
      outfit.isLiked = response.data.liked
      if (response.data.liked) {
        outfit.like_count = (outfit.like_count || 0) + 1
      } else {
        outfit.like_count = Math.max(0, (outfit.like_count || 0) - 1)
      }
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 显示评论
const showComments = async (outfit) => {
  currentOutfit.value = outfit
  commentDialogVisible.value = true
  await loadComments(outfit.id)
}

// 加载评论
const loadComments = async (outfitId) => {
  try {
    loadingComments.value = true
    const response = await socialAPI.getOutfitComments(outfitId, {
      page: 1,
      pageSize: 50
    })

    if (response.code === 200) {
      comments.value = response.data.list || []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  } finally {
    loadingComments.value = false
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    submittingComment.value = true
    const response = await socialAPI.commentOutfit(currentOutfit.value.id, {
      content: newComment.value,
      rating: commentRating.value || null
    })

    if (response.code === 200) {
      ElMessage.success('评论发表成功')
      newComment.value = ''
      commentRating.value = 0
      
      // 更新评论列表
      await loadComments(currentOutfit.value.id)
      
      // 更新搭配的评论数
      currentOutfit.value.comment_count = (currentOutfit.value.comment_count || 0) + 1
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  } finally {
    submittingComment.value = false
  }
}

// 回复评论
const replyComment = (comment) => {
  newComment.value = `@${comment.user?.username} `
}

// 点赞评论
const likeComment = async (comment) => {
  // 这里应该实现评论点赞功能
  console.log('点赞评论:', comment)
}

// 分享搭配
const shareOutfit = (outfit) => {
  // 这里应该实现分享功能
  console.log('分享搭配:', outfit)
  ElMessage.success('分享链接已复制到剪贴板')
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays}天前`
  if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`
  return date.toLocaleDateString('zh-CN')
}

// 页面初始化
onMounted(() => {
  loadOutfits()
})
</script>

<style scoped>
.discover-tab {
  space-y: 20px;
}

.filter-bar {
  margin-bottom: 20px;
}

.outfits-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.outfit-card {
  width: 100%;
}

.outfit-image-container {
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 12px;
}

.outfit-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.outfit-image:hover {
  transform: scale(1.05);
}

.outfit-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  padding: 12px;
  opacity: 0;
  transition: opacity 0.3s;
}

.outfit-image-container:hover .outfit-overlay {
  opacity: 1;
}

.outfit-stats {
  display: flex;
  gap: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: white;
  font-size: 12px;
}

.outfit-info {
  padding: 12px;
}

.outfit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.outfit-title {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.outfit-tags {
  margin-bottom: 12px;
}

.outfit-tags .el-tag {
  margin-right: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.user-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
}

.username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-right: 8px;
}

.publish-time {
  font-size: 12px;
  color: #999;
  margin-left: auto;
}

.outfit-actions {
  display: flex;
  gap: 8px;
}

.load-more {
  text-align: center;
  margin: 40px 0;
}

.comments-container {
  max-height: 500px;
  overflow-y: auto;
}

.comments-list {
  margin-bottom: 20px;
}

.comment-item {
  display: flex;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 12px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.comment-username {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-right: 8px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  margin: 8px 0;
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  gap: 12px;
}

.comment-form {
  border-top: 1px solid #eee;
  padding-top: 16px;
}

.comment-form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .outfits-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }
  
  .outfit-actions {
    flex-direction: column;
  }
  
  .outfit-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
